const Navigation = require('../models/Navigation')
const NaviCategory = require('../models/NaviCategory')
const { uploadURL } = require("../config");


exports.addNavigation = async function (req, res, next) {
  let body = req.body;
  console.log("body: ", body);
  if (body.navigation_icon) {
    body.navigation_icon = body.navigation_icon.replace(uploadURL, "");
  } else {
    body.cover = "/img/web.png";
  }
  try {
    await Navigation.create(body);
    res.success("导航添加成功");
  } catch (err) {
    next(err);
  }
}


exports.delNavigation = async function (req, res, next) {
  let _id = req.params.id
  try {
    await Navigation.findByIdAndDelete(_id)
    res.success('导航删除成功')
  } catch (err) {
    next(err)
  }
}
exports.updateNavigation = async function (req, res, next) {
  let _id = req.params.id
  let body = req.body;
  if (body.navigation_icon) {
    body.navigation_icon = body.navigation_icon.replace(uploadURL, "");
  } else {
    body.cover = "/img/web.png";
  }
  try {
    await Navigation.findByIdAndUpdate(_id, body)
    res.success('导航更新成功')
  } catch (err) {
    next(err)
  }
}
exports.getNavigationList = async function (req, res, next) {
  try {
    // 查询所有分类
    const categories = await NaviCategory.find().sort({ sort: 1 });
    // 使用Promise.all来等待所有分类的导航条目查询完成
    const categoryPromises = categories.map(async (category) => {
      try {
        // 对每个分类使用populate来获取其下的导航条目
        let navigations = await Navigation.find({
          navigation_category: category._id,
        })
          .populate("navigation_category")
          .exec();
        navigations = navigations.map((navigation) => {
          return {
            _id: navigation._id,
            navigation_name: navigation.navigation_name,
            navigation_link: navigation.navigation_link,
            navigation_category: navigation.navigation_category,
            navigation_icon: uploadURL + navigation.navigation_icon,
            navigation_intro: navigation.navigation_intro,
          };
        });
        // 构建每个分类的导航列表对象
        return { name: category.name, _id: category._id, navigations };
      } catch (error) {
        console.error(error);
        throw error; // 重新抛出错误，以便Promise.all可以捕获它
      }
    });
    // 等待所有Promise完成
    const arr = await Promise.all(categoryPromises);

    console.log('arr:', arr);
    res.success(arr, '获取导航列表成功');
  } catch (err) {
    next(err)
  }
}


exports.getNavigationDetail =  async function (req, res, next){
  const navigationId = req.params.id
  try {
    const navigation = await Navigation.findById(navigationId).populate(
      "navigation_category"
    );
    navigation.navigation_icon = uploadURL + navigation.navigation_icon;
    res.success(navigation, "导航详情查询成功");
  } catch (err) {
    console.log("err: ", err);
  }
}
